<?php
/***************************************************************
*  Copyright notice
*  (c) 2009, jianyuzhu@gmail.com
*  All rights reserved
*  This script is part of the PPEMI project.
***************************************************************/

//
function func_gzip_check() {
	$http_accept_encoding = $_SERVER['HTTP_ACCEPT_ENCODING'];
	if( headers_sent() || connection_aborted() ) {
		return false;
	}
	if( strpos($http_accept_encoding, 'x-gzip') !== false ) {
		return 'x-gzip';
	}
	if( strpos($http_accept_encoding, 'gzip') !== false ) {
		return 'gzip';
	}
	
	return false;
}

function func_gzip_start($gzip_enabled = false, $gzip_level = 5) {
	//if gzip_compression is enabled, start to buffer the output
	global $gzip_compression_enabled;
	global $ext_zlib_loaded;
	global $ini_zlib_output_compression;
	global $gzip_level;
	
	$gzip_compression_enabled = $gzip_enabled;
	$ext_zlib_loaded = extension_loaded('zlib');
	$gzip_level = 5;
	if( ($gzip_compression_enabled == true) && ($ext_zlib_loaded) && (PHP_VERSION >= '4') ) {
		$ini_zlib_output_compression = (int)ini_get('zlib.output_compression');
		if( $ini_zlib_output_compression < 1 ) {
			if( PHP_VERSION >= '4.0.4' ) {
				ob_start('ob_gzhandler');
			} else {
				ob_start();
				ob_implicit_flush();
			}
		} else {
			ini_set('zlib.output_compression_level', $gzip_level);
		}
	}
}

/* $level = compression level 0-9, 0=none, 9=max */
function func_gzip_output($level = 5) {
	$encoding = func_gzip_check();
	if( $encoding ) {
		$content = ob_get_contents();
		ob_end_clean();
		
		header('Content-Encoding: ' . $encoding);
		
		$size = strlen($content);
		$crc = crc32($content);
		
		$content = gzcompress($content, $level);
		$content = substr($content, 0, strlen($content) - 4);
		
		echo "\x1f\x8b\x08\x00\x00\x00\x00\x00";
		echo $content;
		echo pack('V', $crc);
		echo pack('V', $size);
	} else {
		ob_end_flush();
	}
}

function func_gzip_end() {
	global $gzip_compression_enabled;
	global $ext_zlib_loaded;
	global $ini_zlib_output_compression;
	global $gzip_level;
	
	if( ($gzip_compression_enabled == true) && ($ext_zlib_loaded == true) && ($ini_zlib_output_compression < 1) ) {
		if( PHP_VERSION >= '4' && PHP_VERSION < '4.0.4' ) {
			func_gzip_output($gzip_level);
		}
	}
}
//
?>